<template>
  <div class="employees-container">
    <div class="app-container">
      <pageToole>
        <template #left>
          <span>总共:{{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/employees/import')">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExcel">导出excel</el-button>
          <el-button v-allow="'add_employee'" type="primary" size="small" @click="dialogVisible=true">新增员工</el-button>
        </template>

      </pageToole>

      <el-card style="margin-top:20px">
        <el-table :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="{row}">
              <ImageHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <!-- row.formOfEmployment=后台返回的以供枚举的状态码 -->
            <!-- 定义一个函数,用来枚举employees.js里面的数组的数据,让数组里面的数据状态决定数据的状态 -->
            <template v-slot="{row}">
              {{ employees(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ formatData(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push('/employees/detail/' + row.id )">查看</el-button>
              <el-button v-allow="'assign_roles'" type="text" @click="hAssignRole(row.id) ">分配角色</el-button>
              <el-button v-allow="'delete_employee'" type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog
          title="新增员工"
          :visible.sync="dialogVisible"
          width="50%"
        >
          <dialogForm v-if="dialogVisible" @success="success" />
        </el-dialog>
        <el-pagination
          :current-page="q.page"
          :page-sizes="[2, 5, 7, 10]"
          :page-size="q.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-dialog
          title="分配角色"
          :visible.sync="showDialog"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          width="50%"
        >
          <assign-role v-if="showDialog" :id="curId" @close="showDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入枚举数据
import dayjs from 'dayjs'
import employees from '@/constant/employees'
import { delEmployee, getEmployee } from '@/api/employess'
import dialogForm from '@/views/employees/dialogForm.vue'
import AssignRole from './assignRole'

const hireTypeMap = {}
employees.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  name: 'VueAdminTemplateEmployees',
  components: { dialogForm, AssignRole },

  data() {
    return {
      dialogVisible: false,
      showDialog: false,
      curId: '',
      list: [],
      total: 0,
      q: {
        page: 1,
        size: 5
      }
    }
  },

  created() {
    this.loadEmployee()
  },

  methods: {
    async  loadEmployee() {
      const res = await getEmployee(this.q)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 定义一个方法,接收后台返回的以供枚举的状态码
    // 这里的code就是后台返回的以供枚举的状态码
    // employees(code) {
    //   // 枚举constant文件夹已经写好了的,规定各种属性的,各种状态的数组
    //   // 让后台返回的数据与数组里面的状态码进行匹配,根据状态码来决定页面的数据
    //   const resuit = employees.hireType.find(item => item.id === code)
    //   // 提高代码的健壮性
    //   if (resuit) {
    //     return resuit.value
    //   } else {
    //     return '未知'
    //   }
    // }
    employees(code) {
      return hireTypeMap[code]
    },
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployee()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployee()
    },
    async  hDel(id) {
      try {
        await this.$confirm('真的要删除吗', '提示', { type: 'warning' })
        const res = await delEmployee(id)
        this.$message.success(res.message)
        // if (this.total % this.q.page) {
        //   this.total++
        // }
        // this.q.page = Math.ceil(this.total / this.q.page)

        if (this.list.length === 1 && this.q.page > 0) {
          this.q.page--
        }
        this.loadEmployee()
      } catch (e) {
        this.$message.success(e.message)
      }
    },
    success() {
      this.dialogVisible = false
      this.loadEmployee()
    },
    formatData(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    async hExcel() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await getEmployee({ page: 1, size: this.total })
      // list获取员工信息
      const list = res.data.rows
      // 因为每个人的信息都只有一条，所以只取第一条数据
      const first = list[0]
      // 如果没有数据就返回
      if (!first) return
      // 设置表头，把英文转化成中文
      // 1.得到所有英文key，map迭代数组，把英文key转化为中文
      // 2.Object.keys得到英文key：id ，password，mobile ...
      // 3.用以及得到的英文key的数组迭代已经准备好的数组，换位中文
      const header = Object.keys(first).map(enkey => mapInfo[enkey])
      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        return Object.values(item)
      })
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header, // 表头, 传入一个数组
        data, // 数据, 传入一个二维数组 [ [] ] , 二维数组里面的数组就是一条数据
        filename: '员工数据', // 导出的文件名称
        autoWidth: true, // 自适应宽度
        bookType: 'xlsx' // 文件类型
      })
    },
    hAssignRole(id) {
      this.showDialog = true
      this.curId = id
    }

  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
